package com.langshixiaobai.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.langshixiaobai.admin.common.convention.result.Result;
import com.langshixiaobai.admin.common.utils.UserContext;
import com.langshixiaobai.admin.dao.entity.GroupDO;
import com.langshixiaobai.admin.dao.entity.UserDO;
import com.langshixiaobai.admin.dao.mapper.GroupMapper;
import com.langshixiaobai.admin.dto.req.ShortLinkGroupSaveReqDTO;
import com.langshixiaobai.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.langshixiaobai.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.langshixiaobai.admin.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.langshixiaobai.admin.dto.resp.ShortLinkGroupRespDTO;
import com.langshixiaobai.admin.service.GroupService;
import com.langshixiaobai.admin.service.ShortLinkRemoteService;
import com.langshixiaobai.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {


    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };

    @Override
    public void saveGroup(String groupName) {
        String gid;
        // idea 自动优化
        // 通过循环判断来找到不重复的gid
        do {
            gid = RandomGenerator.generateRandom();
        } while (!hasGid(gid));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .username(UserContext.getUsername())
                .name(groupName)
                .sortOrder(0)
                .build();
        baseMapper.insert(groupDO);
    }
    //放gid重复
    public boolean hasGid(String gid){
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                   // TODO 设置用户名
                 .eq(GroupDO::getUsername, UserContext.getUsername());
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO == null;
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> wrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder);
        List<GroupDO> groupDOList = baseMapper.selectList(wrapper);
        List<String> requestParam = groupDOList.stream().map(GroupDO::getGid).toList();
        //远程调用
        Result<List<ShortLinkGroupCountQueryRespDTO>>shortLink = shortLinkRemoteService.countShortLink(requestParam);

        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        // stream流遍历存储
        shortLinkGroupRespDTOList.forEach(each ->{
            Optional<ShortLinkGroupCountQueryRespDTO> optional = shortLink.getData().stream().filter(item -> item.getGid().equals(each.getGid()))
                    .findFirst();
        optional.ifPresent(item->each.setShortLinkCount(optional.get().getShortLinkCount()));
        });

        List<ShortLinkGroupRespDTO> groupRespDTOS = BeanUtil.copyToList(shortLinkGroupRespDTOList, ShortLinkGroupRespDTO.class);
        return groupRespDTOS;
    }

    // 修改分组
    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> wrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        //进行修改
        GroupDO groupDO = GroupDO.builder().name(requestParam.getName()).build();
        baseMapper.update(groupDO, wrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {

        requestParam.forEach(each ->{

            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();

            LambdaUpdateWrapper<GroupDO> wrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .set(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO, wrapper);
        });

    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = GroupDO.builder().delFlag(1).build();
        baseMapper.update(groupDO, updateWrapper);
    }
}
